/*
"JSFXGEN" - Main_online.as
Modular Integrated Development Environment for JesuSonic
Project page: http://jsfxgen.googlecode.com

Copyright 2009 Lubomir I. Ivanov

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package 
{
  // =========================================================
  // [ import
  // =========================================================
  import flash.display.Bitmap;
  import flash.display.Sprite;
  import flash.display.Stage;
  import flash.display.StageAlign;
  import flash.display.StageScaleMode;
  import flash.display.StageQuality;
  import flash.display.DisplayObject;
  import flash.display.DisplayObjectContainer;
  import flash.geom.Rectangle;
  import flash.events.IEventDispatcher;
  import flash.events.Event;
  import flash.events.MouseEvent;
  import flash.system.fscommand;
  import flash.net.URLLoader;
  import flash.net.URLRequest;
  import flash.text.TextField;
  import flash.text.TextFieldAutoSize;
  import flash.text.TextFormat;
  import neolit123.ui.Box;
  import neolit123.ui.UIButton;
  import neolit123.ui.UIList;
  import neolit123.ui.Debug;
  import neolit123.ui.Loading;
  import neolit123.ui.Dialog;
  import neolit123.ui.ToolTip;
  import neolit123.jsfxgen.Module;
  import neolit123.jsfxgen.Connection;
  import neolit123.jsfxgen.Editor;
  import neolit123.jsfxgen.Cross;
  import neolit123.jsfxgen.JSParser;
  import neolit123.jsfxgen.Arranger;
  // @ air
  /*
  import flash.filesystem.File;
  import flash.filesystem.FileMode;
  import flash.filesystem.FileStream;  
  import flash.net.FileFilter;
  import flash.utils.ByteArray;
  import flash.desktop.NativeApplication;
  import flash.display.NativeWindow;
  import flash.events.InvokeEvent;
  import flash.events.FileListEvent;
  */
  // =========================================================
  // [ main class
  // =========================================================
  public class Main extends Sprite
  {
    // =========================================================
    // [ variables and constants
    // =========================================================
    // @ private    
    private var vbuild:String;
    private var modpath:String;    
    private var df:Function;
    private var btnholder:Sprite;
    private var ptxt:TextField;
    private var tf:TextFormat = new TextFormat("_sans", 10);
    private var list:UIList;
    private var btn:UIButton;
    private var loader:URLLoader = new URLLoader();
    private var request:URLRequest = new URLRequest();    
    private var listarray:Array = [];
    private var module:Module;
    private var mblank:Box;
    private var logo:Bitmap = new Bitmap(new Logo(0,0));
    private var hbkg:Box;
    private var filesep:String = "/";
    private var numch:int;
    private var date:Date;
        private static var _ver:Version = new Version("(online)");
        private var __copyright:Copyright = new Copyright();
        private var _copyright:String = __copyright.get();
    // @ public static
    public static const bkgcolor:int = 0x666666;
    public static const thmcolor:int = 0xdddddd; //0x9ad8ff;
    public static const modtextcolor:int = 0x000000;
    public static const modbordercolor:int = 0x000000;
    public static const listwidth:Number = 150;    
    public static var version:String = _ver.get();
    public static var conlen:int;
    public static var listheight:Number = 400;
    public static var sw:Number;
    public static var sh:Number;
    public static var swd:Number;
    public static var m_ar:Array = [];
    public static var _instance:Main = null;
    public static var dialog:Dialog;
    public static var editor:Editor;
    public static var initX:Number;    
    public static var initY:Number;
    public static var dodraw:Boolean = false;
    public static var movemodule:Boolean = false;
    public static var consource:Object = null;
    public static var condest:Object = null;
    public static var connections:Array = [];
    public static var parser:JSParser;
    public static var bkg:Box;
    public static var mcd:Sprite;
    public static var lines:Sprite;
    public static var tt:ToolTip;
    public static var tmpline:Sprite;
    public static var mc:Sprite;
    public static var loading:Loading;
    public static var debug:Debug;
    public static var arranger:Arranger;
    // =========================================================
    // [ main
    // =========================================================
    public function Main():void
    {
      _instance = this;
      if (stage) loadvbuild();
      else addEventListener(Event.ADDED_TO_STAGE, loadvbuild);
    }
    // =========================================================
    // [ load vbuild
    // =========================================================
    private function loadvbuild(e:Event = null):void
    {      
      // ----------------------------------
      // [ set stage
      // ----------------------------------
      stage.stageFocusRect = false;
      sw = stage.stageWidth;
      sh = stage.stageHeight;
      //stage.quality = StageQuality.LOW;
      stage.scaleMode = StageScaleMode.NO_SCALE;
      stage.align = StageAlign.TOP_LEFT;
      stage.addEventListener(Event.RESIZE, stageresize);
      // @ add loading
      loading = new Loading(0x000000,0xffffff);
      stage.addChild(loading);
      // @ add tooltip
      tt = new ToolTip();
      stage.addChild(tt);
      // @ add debug
      debug = new Debug();
      stage.addChild(debug);
      df = debug.df;
      debug.x = sw - 25;
      debug.y = sh - 25;
      // @ add dialog
      dialog = new Dialog(0x000000,0xffffff,thmcolor,0x000000);
      stage.addChild(dialog);
      // ----------------------------------
      // [ set window
      // ----------------------------------
      //stage.nativeWindow.title = "JSfxGEN "+version;
      // ----------------------------------
      // [ exit listener
      // ----------------------------------
      //stage.nativeWindow.addEventListener(Event.CLOSING, exitdialog);
      function exitdialog(e:Event):void
      {
        e.preventDefault();
        df("Exit dialog", false);
        //stage.nativeWindow.restore();
        dialog.update("Are you sure you want to exit?", "Yes", "Cancel", doexit, dialog.close);
        // @ remove this line
        //doexit();
      }        
      function doexit():void
      {
        //NativeApplication.nativeApplication.exit();         
      }        
      // ----------------------------------
      // [ begin load
      // ----------------------------------
      loading.update("Loading VBUILD");
      request = new URLRequest("vbuild");
      loader.addEventListener(Event.COMPLETE, vbuildcomplete);
      try {
        loader.load(request);
      } catch (error:Error) {
        loading.error(error.message);
      }
    }
    // =========================================================
    // [ load list of modules
    // =========================================================
    private function vbuildcomplete(event:Event):void
    {      
      var loader:URLLoader = URLLoader(event.target);
      vbuild = loader.data;
      df("DEBUG JSFXGEN\nv: "+version+"\nb: "+vbuild+"\n--------------", false);
      // @ load list of modules
      loading.update("Loading list of modules");
      // @ get local files
      modpath = "modules";
      
      // @ ------- online version
      date = new Date();      
      request = new URLRequest("modules.cfg?"+date.getTime());
      loader = new URLLoader();
      loader.addEventListener(Event.COMPLETE, init);
      try {
        loader.load(request);
      } catch (error:Error) {
        loading.error(error.message);
      }      
    }
    // =========================================================
    // [ init (start here)
    // =========================================================
    private function init(event:Event):void
    {
      df("List of modules loaded (total: "+listarray.length.toString()+")");
      var i:int;      
      // ----------------------------------
      // [ add objects / containers
      // ----------------------------------
      // @ add parser
      parser = new JSParser;
      // @ add module and lines holder
      mcd = new Sprite;
      stage.addChild(mcd);
      // @ add bkg
      var bkgdim:Number = 3000; 
      bkg = new Box(bkgdim,bkgdim,bkgcolor,bkgcolor);
      mcd.addChild(bkg);      
      // @ draw grid
      var nc:int = bkgdim/200;
      for (i=0;i<nc;i++) {
        for (var j:int=0;j<nc;j++) {
          var cross:Cross = new Cross(70,i,j);
          bkg.addChild(cross);
          cross.x = 100+200*i;
          cross.y = 100+200*j;
        } 
      }
      bkg.cacheAsBitmap = true;
      // @ add line connections  
      lines = new Sprite;
      mcd.addChild(lines);
      // @ add logo      
      // ----- stage.addChild(logo);
      // @ add tmp line
      tmpline = new Sprite;
      mcd.addChild(tmpline);
      // @ add module container
      mc = new Sprite();      
      mcd.addChild(mc);
      mcd.x = listwidth;
      // @ add blank module
      mblank = new Box(1,1,0xff0000,0xff0000);
      mblank.alpha = 0;
      mc.addChild(mblank);
      // @ add button holder
      btnholder = new Sprite;
      stage.addChild(btnholder);
      // @ add list
      list = new UIList(100,listwidth);
      stage.addChild(list);
      // @ add editor
      arranger = new Arranger;
      stage.addChild(arranger);
      // @ add editor
      editor = new Editor;
      stage.addChild(editor);
      // @ sort containers z index
      numch = stage.numChildren;
      with (stage) {
        // @ set indexes for stage
        setChildIndex(tt, numch-1);
        setChildIndex(debug, numch-2);
        setChildIndex(dialog, numch-3);
        setChildIndex(loading, numch-4);
        setChildIndex(editor, numch-5);
        setChildIndex(arranger, numch-6);
        setChildIndex(list, numch-7);
        setChildIndex(btnholder, numch-8);
        setChildIndex(mcd, numch-9);
        // @ set indexes for module container
        mcd.setChildIndex(mc, 3);
        mcd.setChildIndex(tmpline, 2);
        mcd.setChildIndex(lines, 1);
        mcd.setChildIndex(bkg, 0);
      }
      // ----------------------------------
      // [ fill list online version
      // ----------------------------------
          
      var loader:URLLoader = URLLoader(event.target);
      var modlist:String = loader.data.toString();      
      listarray = modlist.split("\r\n");
      //df(listarray);
      listarray.sort();
      listarray.shift();
      var listarraylen:int = listarray.length;
      for (i=0;i<listarraylen;i++) {
        list.additem(listarray[i].split(".jsmod").join(""), listarray[i]);
        // @ add doubleclick
        list.btn.addEventListener(MouseEvent.DOUBLE_CLICK, btndclick);
        function btndclick(e:MouseEvent = null):void
        {   
          loadmodule(listarray[list.selecteditem.id]);
        }
      }
      list.select(0);
           
      // @ create buttons
      createbuttons();
      
      // --------------------------------------------
      // [ drag work area
      // --------------------------------------------
      bkg.buttonMode = true;  
      bkg.mouseChildren = false;      
      bkg.addEventListener(MouseEvent.MOUSE_DOWN, wadrag);
      function wadrag(e:MouseEvent=null):void 
      {
          var rx:Number,ry:Number,rw:Number,rh:Number;
          rx=Math.min(sw-bkg.width,0);
          ry=Math.min(sh-bkg.height,0);
          rw=Math.max(bkg.width-swd,0);
          rh=Math.max(bkg.height-sh,0);
          var rect:Rectangle = new Rectangle(rx,ry,rw,rh);
          stage.addEventListener(MouseEvent.MOUSE_UP, wastop);
          mcd.startDrag(false,rect);
      }
      function wastop(e:MouseEvent):void 
      {
        stage.removeEventListener(MouseEvent.MOUSE_UP, wastop);
        mcd.stopDrag();
      }
      // --------------------------------------------
      // [ move tt / draw tmp line / redraw modules
      // --------------------------------------------
      stage.addEventListener(MouseEvent.MOUSE_MOVE, movett);
      function movett(e:MouseEvent=null):void
      {
        // @ draw line
        if (dodraw)
        {
          with (tmpline.graphics)
          {
            clear();
            lineStyle(1,thmcolor,1);
            moveTo(initX,initY);
            lineTo(stage.mouseX-mcd.x, stage.mouseY-mcd.y);
          }
        }
        // @ !tmp! redraw connections on module move
        else if (movemodule) redrawconnections();        
      }
      // ----------------------------------
      // [ clear tmpline on mouse release
      // ----------------------------------
      stage.addEventListener(MouseEvent.MOUSE_UP, mrelease);
      function mrelease(e:MouseEvent=null):void
      {
        if (dodraw)
        {
          // @ only if drawing tmpline 
          tmpline.graphics.clear();
          if ((condest != null) && (condest.active == true && consource.isinput != condest.isinput && consource.parentid != condest.parentid))
          {
            // @ add a connection            
            var cl:int = connections.length+1;
            for (var i:int=0;i<cl;i++)
            {
              if (connections[i] == undefined) break;
            }
            if (!consource.isinput) addconnection(consource, condest, i) else addconnection(condest, consource, i);  
            consource = condest = null;
          } else {
             df("ROUTING - destination not accepted",false);
          }
          dodraw = false;
        }
      }
      // ----------------------------------
      // [ init
      // ----------------------------------
      //NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, oninvoke);
      loading.visible = false;
      stageresize();
    }
    // =========================================================
    // [ add connection
    // =========================================================
    public function addconnection(consource:Object,condest:Object, idx:int):void {
      var connection:Connection = new Connection(consource,condest, idx);
      lines.addChild(connection);
      connections[idx] = connection;
      conlen = connections.length;
    }
    // =========================================================
    // [ redraw connections
    // =========================================================
    public function redrawconnections():void {     
        for (var i:int=0;i<conlen;i++)
        {
          if (connections[i] != undefined) connections[i].redraw();
        }
    }  
    // =========================================================
    // [ get stage and main
    // =========================================================
    public static function getmain():Main { return _instance; }
    // =========================================================
    // [ stage resize
    // =========================================================
    private function stageresize(e:Event = null):void
    {
      // @ get stage width / height
      sw = stage.stageWidth;
      swd = stage.stageWidth-listwidth;
      sh = stage.stageHeight;
      // @ align items to stage
      debug.x = sw-25;
      debug.y = sh-25;
      listheight = btnholder.y = sh-btnholder.height;
      list.setsize(listwidth,listheight);
      editor.align(sw,sh);
      loading.align(sw,sh);
      dialog.align(sw,sh);
      arranger.align(sw,sh);
      // @ align logo, mcd -> (disabled)
      //mcd.x = listwidth;
      //mcd.y = 0;
      //logo.x = (listwidth-logo.width)*0.5;
      //logo.y = sh-logo.height-10;
    }
    // ----------------------------------
    // [ create buttons
    // ----------------------------------
    private function createbuttons():void
    {             
      // @ add holder bkg
      hbkg = new Box(listwidth-1,100,0xfafafa,0xfafafa);
      btnholder.addChild(hbkg);
      // @ add projet ttxt
      ptxt = new TextField;
      btnholder.addChild(ptxt);
      ptxt.x = listwidth+8;
      with (ptxt)
      {
        tf.leftMargin = tf.rightMargin = 5;
        defaultTextFormat = tf;
        border = true;
        selectable = false;
        background = true;
        backgroundColor = 0x999999;
        autoSize = "left";
        text = "file: New Project";
      }
      // @ ------------------------
      // @ add module      
      btn = new UIButton("Add module");
      btnholder.addChild(btn);
      btn.y = 20;
      btn.x = (listwidth-btn.width)*0.5;
      var btnx:Number = btn.x;      
      btn.addEventListener(MouseEvent.CLICK, addmod);
      function addmod(e:MouseEvent = null):void 
      {
        loadmodule(listarray[list.selecteditem.id]);
      }
      // @ new module      
      var btnh:Number = btn.height;
      var btny:Number = btn.y+btnh;
      btn = new UIButton();
      btnholder.addChild(btn);
      btn.y = btny;
      btn.x = btnx;
      btn.setlabel("New module");
      btn.addEventListener(MouseEvent.CLICK, newmod);
      function newmod(e:MouseEvent = null):void
      {
        loadmodule("new");
      }
      // @ delete all
      btny += btnh+10;
      btn = new UIButton();
      btnholder.addChild(btn);
      btn.y = btny;
      btn.x = btnx;
      btn.setlabel("Delete all");
      btn.addEventListener(MouseEvent.CLICK, deleteall);
      function deleteall(e:MouseEvent = null):void
      {
        if (mc.numChildren > 1) {
          dialog.update("This will delete all modules. Are you sure?", "Ok", "Cancel", deleteallmodules, dialog.close);
        }
      }      
      // @ minimize all
      btny += btnh;
      btn = new UIButton();
      btnholder.addChild(btn);
      btn.y = btny;
      btn.x = btnx;
      btn.setlabel("Minimize all");
      btn.addEventListener(MouseEvent.CLICK, minall);
      function minall(e:MouseEvent = null):void
      {
        minimizeall();
      }      
      // @ maxmimize all
      btny += btnh;
      btn = new UIButton();
      btnholder.addChild(btn);
      btn.y = btny;
      btn.x = btnx;
      btn.setlabel("Maximize all");
      btn.addEventListener(MouseEvent.CLICK, maxall);
      function maxall(e:MouseEvent = null):void 
      {
         maximizeall();
      }
      // @ generate js
      btny += btnh+10;
      btn = new UIButton();
      btnholder.addChild(btn);
      btn.y = btny;
      btn.x = btnx;
      btn.setlabel("Generate JS");
      btn.addEventListener(MouseEvent.CLICK, generatejs);
      function generatejs(e:MouseEvent = null):void
      {
        if (m_ar.length > 0) parser.process();
      }
      // @ open
      btny += btnh+10;
      btn = new UIButton();
      btnholder.addChild(btn);
      btn.y = btny;
      btn.x = btnx;
      btn.setlabel("Open project");
      btn.addEventListener(MouseEvent.CLICK, openclick);
      function openclick(e:MouseEvent = null):void
      {
        /*
        var file:File = File.applicationDirectory;
        file.addEventListener(Event.SELECT, doopenevent);
        file.browseForOpen("Open JSfxGen file",[new FileFilter("JSfxGen files", "*.jsfxgen")]);
        */
      }
      btn.enable(false);
      // @ save
      btny += btnh;
      btn = new UIButton();
      btnholder.addChild(btn);
      btn.y = btny;
      btn.x = btnx;
      btn.setlabel("Save project");      
      btn.addEventListener(MouseEvent.CLICK, saveclick);
      function saveclick(e:MouseEvent = null):void
      {
        /*
        var file:File = File.applicationDirectory.resolvePath("*.jsfxgen");
        file.browseForSave("Save JSfxGen file");
        file.addEventListener(Event.SELECT, dosave);
        */ 
      }
      btn.enable(false);
      // @ save
      btny += btnh;
      btn = new UIButton();
      btnholder.addChild(btn);
      btn.y = btny;
      btn.x = btnx;
      btn.setlabel("Arrange");
      btn.addEventListener(MouseEvent.CLICK, projectsettings, false, 0, true);
      function projectsettings(e:MouseEvent = null):void {        
        arranger.open();
      }
      // @ about
      btny += btnh+10;
      btn = new UIButton();
      btnholder.addChild(btn);
      btn.y = btny;
      btn.x = btnx;
      btn.setlabel("About");
      btn.addEventListener(MouseEvent.CLICK, aboutf);
      function aboutf(e:MouseEvent = null):void {
        var longtext:String = "JSFXGEN "+version+"\n"+_copyright;
        dialog.update(longtext, "Ok", "---", dialog.close, dialog.close);
      }  
      
      // @ set bkg height
      hbkg.height = btnholder.height+20;
      ptxt.y = hbkg.height-28; 
    }
    // =========================================================
    // [ add module
    // =========================================================
    public function loadmodule(str:String):void
    {
      // @ add mod      
      function addmod(nstr:String, dta:String):void 
      {
        var marlen:int = m_ar.length+1;
        var tgti:int;
        for (var i:int=0;i<marlen;i++) {
          if (m_ar[i] == undefined || m_ar[i] == null)
          { tgti = i; break; }          
        }
        // @ add module to main array and stage
        module = new Module(nstr.split(".jsmod").join(""),dta,tgti);
        mc.addChild(module);
        m_ar[tgti] = module;
        // @ add module 0,0 coordinates to arrange array
        arranger.xyar[tgti] = [];
        arranger.xyar[tgti] = [0,0];
        // @ set x,y in module container
        module.x = Math.max(mcd.x*(-1)+listwidth,0)+20+Math.random()*90;
        module.y = Math.max(mcd.y*(-1),0)+20+Math.random()*90;
        // @ df
        df("ADD Module [ "+tgti+" ]");        
      }
      // @ check if new
      if (str != "new") {
        request = new URLRequest(modpath+filesep+str);
        loader = new URLLoader();
        loader.addEventListener(Event.COMPLETE, done);
        loading.update("Loading "+modpath+filesep+str);
        try {
        loader.load(request);
        } catch (error:Error) {
        loading.error("Cannot load - "+modpath+filesep+str);
        }
        // @ done
        function done(e:Event=null):void {
        loading.visible = false;
        addmod(str,loader.data);
        }
      } else {
        addmod(str, loader.data);
      }      
    }
    // =========================================================
    // [ delete all modules
    // =========================================================
    private function deleteallmodules():void
    {
      df("Delete all modules!");
      // @ remove mod container
      mcd.removeChild(mc);
      mc = null;
      mc = new Sprite();      
      mcd.addChild(mc);      
      // @ add blank module
      mblank = new Box(1,1,0xff0000,0xff0000);
      mblank.alpha = 0;
      mc.addChild(mblank);
      // @ remove lines      
      mcd.removeChild(lines);
      lines = null;
      lines = new Sprite();
      mcd.addChild(lines);
      // @ refresh depth
      mcd.setChildIndex(mc,3);
      mcd.setChildIndex(tmpline,2);
      mcd.setChildIndex(lines,1);
      mcd.setChildIndex(bkg,0);
      // @ clear arrays
      m_ar = [];      
      connections = [];
      arranger.xyar = [];
      // @ moveto 0,0 and close
      mcd.x = listwidth;
      mcd.y = 0;
      dialog.close();
    }
    // =========================================================
    // [ minimize all
    // =========================================================
    private function minimizeall():void
    {
      df("MINimize all modules");
      var marlen:int = m_ar.length;
      if (marlen > 0) {
        for (var i:int=0;i<marlen;i++) {
          if (m_ar[i] != undefined) m_ar[i].mhide();
        }
      }
    }
    // =========================================================
    // [ maximize all
    // =========================================================
    private function maximizeall():void
    {
      df("MAXimize all modules");
      var marlen:int = m_ar.length;
      if (marlen > 0) {
        for (var i:int=0;i<marlen;i++) {
          if (m_ar[i] != undefined) m_ar[i].mshow();
        }
      }
    }
    // =========================================================
    // [ do save
    // =========================================================
    private function dosave(event:Event):void
    {
      /*
      loading.update("Saving file");
      // @ prepare object;
      var object:Object = {};
      // @ store x,y
      object.dx = mcd.x;
      object.dy = mcd.y;
      // @ update arranger x,y array
      object.xyar = arranger.xyar;
      // @ set desc, author 
      object.desc = arranger.desc;
      object.author = arranger.author;
      // @ set w,h
      object.w = arranger.w;
      object.h = arranger.h;
      var i:int;
      // @ store module [x,y,id,label,text,maximized,modx,mody]
      var modar:Array = [];
      var marlen:int = m_ar.length;
      for (i=0;i<marlen;i++) {
        modar[i] = [];
        if (m_ar[i] != undefined) 
        {
          modar[i][0] = m_ar[i].x;
          modar[i][1] = m_ar[i].y;
          modar[i][2] = m_ar[i].modid;
          modar[i][3] = m_ar[i].lb;
          modar[i][4] = m_ar[i].moddata;
          modar[i][5] = m_ar[i].sub.visible;
          modar[i][6] = m_ar[i].modx;
          modar[i][7] = m_ar[i].mody;
        }
      }
      // @ store connections [src/dest pin][isinput, index, parentid]
      var conar:Array = [[[]]];
      var conlen:int = connections.length;
      for (i=0;i<conlen;i++) {         
         conar[i] = [];
         conar[i][0] = [];
         conar[i][1] = [];
         if (connections[i] != undefined) {
          // @ src
          conar[i][0][0] = connections[i].src.isinput;
          conar[i][0][1] = connections[i].src.index;
          conar[i][0][2] = connections[i].src.parentid;  
          // @ dest 
          conar[i][1][0] = connections[i].dest.isinput;
          conar[i][1][1] = connections[i].dest.index;
          conar[i][1][2] = connections[i].dest.parentid;
         }
      }
      // @ add arrays to object
      object.modar = modar;
      object.conar = conar;
      // @ get target and write object to stream
      var saveFile:File = File(event.target);
      var directory:String = saveFile.url;
      if(directory.indexOf(".jsfxgen") == -1) directory += ".jsfxgen";      
      var file:File = new File();
      file = file.resolvePath(directory);
      // @ set project txt
      ptxt.text = "File: "+file.name;      
      var fileStream:FileStream = new FileStream();
      fileStream.open(file, FileMode.WRITE);
      fileStream.writeObject(object);
      NativeApplication.nativeApplication.setAsDefaultApplication("jsfxgen");
      // @ close stream
      fileStream.close();
      // @ hide loader
      loading.visible = false;
      df("SAVED: "+file.name); 
      */
    }
    // =========================================================
    // [ do open event
    // =========================================================
    private function doopenevent(e:Event):void
    {
      doopen(e.target);      
    }
    // =========================================================
    // [ do open
    // =========================================================
    private function doopen(tgt:Object):void
    {
      /*
      // -------------------------------------------------------------
      // [ pre
      // -------------------------------------------------------------
      // @ update loading
      df("BEGINLOAD---------------");
      loading.update("Loading arrangement file");
      // @ clear arrays
      connections = [];
      m_ar = [];
      arranger.xyar = [];
      // @ refresh module container
      mcd.removeChild(mc);
      mc = null;
      mc = new Sprite();
      mcd.addChild(mc);
      // @ add blank module
      mblank = new Box(1,1,0xff0000,0xff0000);
      mblank.alpha = 0;
      mc.addChild(mblank);
      // @ refresh lines
      mcd.removeChild(lines);
      lines = null;
      lines = new Sprite();
      mcd.addChild(lines);
      mcd.x = listwidth;
      // @ refresh depth
      mcd.setChildIndex(mc, 3);
      mcd.setChildIndex(tmpline, 2);
      mcd.setChildIndex(lines, 1);
      mcd.setChildIndex(bkg, 0);
      // @ get object from stream
      var file:File = File(tgt);
      var fileStream:FileStream = new FileStream();
      fileStream.open(file, FileMode.READ);
      var object:Object = fileStream.readObject();
      // @ set project txt
      ptxt.text = "File: "+file.name;
      // @ close stream
      fileStream.close();
      // @ get x,y
      mcd.x = object.dx;
      mcd.y = object.dy;
      // @ update arranger x,y array
      arranger.xyar = object.xyar;
      // @ get desc, author  
      arranger.desc = object.desc;
      arranger.author = object.author;
      // @ get w,h
      arranger.w = object.w;
      arranger.h = object.h;
      // -------------------------------------------------------------
      // [ add modules
      // -------------------------------------------------------------    
      var i:int;
      // @ assign array
      var modar:Array = object.modar;
      var modarlen:int = modar.length; 
      // @ add mod function
      function addmod(mx:Number,my:Number,id:int,lb:String,dta:String,viz:Boolean,modx:Number,mody:Number):void
      {
        module = new Module(lb,dta,id);
        mc.addChild(module);
        m_ar[id] = module;
        module.x = mx;
        module.y = my;
        module.modx = modx;
        module.mody = mody;
        if (!viz) module.mhide();
      }
      // @ add all
      for (i=0;i<modarlen;i++) {
        if (modar[i][0] != undefined) addmod(modar[i][0],modar[i][1],modar[i][2],modar[i][3],modar[i][4],modar[i][5],modar[i][6],modar[i][7]);
        
      }
      // -------------------------------------------------------------
      // [ add connections
      // -------------------------------------------------------------
      // @ assign array
      var conar:Array = object.conar;
      var conarlen:int = conar.length;
      var consource:Object;
      var condest:Object;
      // @ add all
      for (i=0;i<conarlen;i++) {
        if (conar[i][0][0] != undefined)
        {
          // @ !isinput
          if (!conar[i][0][0])
          {
            consource = m_ar[conar[i][0][2]].subo.getChildAt(conar[i][0][1]);
            condest = m_ar[conar[i][1][2]].subi.getChildAt(conar[i][1][1]);
          // @ isinput
          } else {
            consource = m_ar[conar[i][0][2]].subi.getChildAt(conar[i][0][1]);
            condest = m_ar[conar[i][1][2]].subo.getChildAt(conar[i][1][1]);
          }
          addconnection(consource,condest,i);
        }
      }
      // --------------------------------
      // @ hide loader
      loading.visible = false;
      df("ENDLOAD---------------");
      */
    }
    // =========================================================
    // [ on invoke
    // =========================================================
    /*  
    private function oninvoke(event:InvokeEvent):void
    {
      if(event.currentDirectory != null && event.arguments.length > 0) {
        var directory:File = event.currentDirectory;        
          doopen(directory.resolvePath(event.arguments[0]));
      }
    }
    */
  }  
}